package com.lfd.service.impl;


import java.util.LinkedList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lfd.mapper.IModuleMapper;
import com.lfd.service.IModuleService;
import com.lfd.vo.ModuleVo;

/**
 * @author tian
 *
 */
@Service
public class ModuleServiceImpl implements IModuleService {
	
	@Autowired
	private IModuleMapper modulMapper;
    /**
          * 获取模块信息
     */
	@Override
	public List<ModuleVo> getModules() {
		 List<ModuleVo> list = modulMapper.selectModules();
		 List<ModuleVo> rootList = this.getRoot(list);
		 this.setChirend(rootList,list);
		 return rootList;
	}
	/**
	  * 设置子节点
	 * @param rootList
	 * @param list
	 */
	private void setChirend(List<ModuleVo> pList, List<ModuleVo> sourcelist) {
		if(CollectionUtils.isNotEmpty(pList) && CollectionUtils.isNotEmpty(sourcelist)) {
			for (ModuleVo moduleVo : pList) {
				if (moduleVo != null) {
					moduleVo.setChildren(new LinkedList());
					Long pid = moduleVo.getId();
					if (pid != null) {
						String pidString = pid.toString();
						for (ModuleVo moduleVo2 : sourcelist) {
							if ( pidString.equals(String.valueOf(moduleVo.getParentId()))) {
								continue;
							}
							if( pidString.equals(String.valueOf(moduleVo2.getParentId()))) {
								moduleVo.getChildren().add(moduleVo2);
							}
						}
					}
					//递归
					this.setChirend(moduleVo.getChildren(), sourcelist);
				}
			}
		}
	}

	/**
	 * 获取根节点
	 */
	private List<ModuleVo> getRoot(List<ModuleVo> list) {
		List<ModuleVo> resList = new LinkedList<ModuleVo>();
		if(CollectionUtils.isNotEmpty(list)) {
			for (ModuleVo moduleVo : list) {
				System.out.println(moduleVo.getParentId() == 0);
				System.out.println(moduleVo.getParentId());
				if ( moduleVo.getParentId() != null && moduleVo.getParentId().toString().equals("0")  ) {
					resList.add(moduleVo);
				}
			}
		}
		return resList;
	}

}
